package rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import org.junit.Test;

import java.nio.charset.StandardCharsets;

public class SimpleQueue {
    private static final String QUEUE_NAME = "simplest-queue";

    @Test
    public void testProducer() throws Exception {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("106.75.12.48");
        factory.setUsername("admin");
        factory.setPassword("admin");
        try (Connection connection = factory.newConnection();
             Channel channel = connection.createChannel()) {
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            String message = "Hello World!你是猪么。。。";
            for (int i = 0; i < 44; i++) {
                String messageContent = message + i;
                channel.basicPublish("", QUEUE_NAME, null, messageContent.getBytes(StandardCharsets.UTF_8));
                System.out.println(" [x] Sent '" + messageContent + "'");
            }

        }
    }

    @Test
    public void testConsumer() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("106.75.12.48");
        factory.setUsername("admin");
        factory.setPassword("admin");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            System.out.println(" [x] Received '" + message + "'");
        };
        // channel.basicQos();
        channel.basicConsume(QUEUE_NAME, true, deliverCallback, consumerTag -> {
        });
        System.out.println("正在监听" + QUEUE_NAME + "队列");
    }
}
